package com.yizisu.playerlibrary.view.video_view.helper

import android.view.View
import android.view.ViewGroup
import androidx.core.view.children

/**
 * view托管默认实现
 */
class PlayerHelper {

    /**
     * 设置监听
     */
    private var hadRegister = false

    fun configPlayerHelper(view: View, config: IPlayerConfig) {
        if (view.isAttachedToWindow) {
            register(view, config)
        }
        view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View?) {
                register(view, config)

            }

            override fun onViewDetachedFromWindow(v: View?) {
                unRegister(view, config)
            }
        })
    }

    /**
     * 遍历所有子view
     */
    private fun findPlayerHelper(view: View, call: Function1<IPlayerHelper, Unit>) {
        if (view is IPlayerHelper) {
            call.invoke(view)
        }
        if (view is ViewGroup) {
            view.children.forEach {
                findPlayerHelper(it, call)
            }
        }
    }

    /**
     * 注册所有事件
     */
    private fun register(view: View, config: IPlayerConfig) {
        if (hadRegister) {
            return
        }
        hadRegister = true
        findPlayerHelper(view) {
            it.onAttachPlayerConfig(config)
            if (it.isNeedPlayerListener()) {
                config.playerData.value?.second?.addPlayerListener(it)
            }
        }
    }

    /**
     * 取消注册所有事件
     */
    private fun unRegister(view: View, config: IPlayerConfig) {
        if (!hadRegister) {
            return
        }
        hadRegister = false
        findPlayerHelper(view) {
            it.onDetachedPlayerConfig(config)
            config.playerData.value?.second?.removePlayerListener(it)
        }
    }
}